package com.kzd.gtboon.main.mine

import android.Manifest
import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import androidx.lifecycle.LifecycleOwner
import com.kzd.gtboon.R
import com.kzd.gtboon.app.AppFlowBus
import com.kzd.gtboon.app.GT_CHANNEL
import com.kzd.gtboon.app.GT_FORCE_LOGIN
import com.kzd.gtboon.app.SPSConstance
import com.kzd.gtboon.custom.setOnClickAntiShakeListener
import com.kzd.gtboon.custom.setTransitionStatus
import com.kzd.gtboon.databinding.ActivityMineUserBinding
import com.kzd.gtboon.entity.IsLogin
import com.kzd.gtboon.entity.UserInfo
import com.kzd.gtboon.jetpack.vm.MineViewModel
import com.kzd.gtboon.main.AccessAction
import com.kzd.gtboon.main.popup.SettingExitPopup
import com.kzd.gtboon.main.toAccessActivity
import com.module.lemlin.app.OwnerStatusBar
import com.module.lemlin.http.Status
import com.module.lemlin.image.loadCircleImage
import com.module.lemlin.owner.OwnerViewBindingActivity
import com.module.lemlin.owner.ownerViewModel
import com.zhihu.matisse.Matisse
import java.lang.StringBuilder

class MineUserActivity : OwnerViewBindingActivity<ActivityMineUserBinding>() {

    private val mSettingExitPopup: SettingExitPopup by lazy {
        SettingExitPopup(context = this, onClick = {
            if (it.id == R.id.tvSettingExitClose) {
                SPSConstance.clearUser()
                AppFlowBus.post(IsLogin::class.java, IsLogin(isLogin = false))
            }
            finish()
        })
    }

    private val mViewModel: MineViewModel by lazy {
        ownerViewModel(owner = this)
    }

    override val inflate: (LayoutInflater) -> ActivityMineUserBinding
        get() = ActivityMineUserBinding::inflate

    override fun initStatusBar(statusBar: OwnerStatusBar) {
        statusBar.run {
            addView = mViewBinding.flMineUserBar
                barColor = R.color.white
        }
        super.initStatusBar(statusBar)
    }

    override fun initView() {

        fillData(SPSConstance.userInfo)

        mViewBinding.flMineUserHeader.setOnClickAntiShakeListener {
            requestDangerousPermissions(arrayOf(
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.CAMERA
            ), requestCode = 1)
        }

        //设置昵称
        mViewBinding.flMineUserNickname.setOnClickAntiShakeListener {
            toAccessActivity(AccessAction.SETTING_NICKNAME)
        }

        //设置QQ
        mViewBinding.flMineUserQQ.setOnClickAntiShakeListener {
            toAccessActivity(AccessAction.SETTING_QQ)
        }

        mViewBinding.flMineUserRealName.setOnClickAntiShakeListener {
            if (SPSConstance.userInfo?.idcard.isNullOrEmpty() ||
                SPSConstance.userInfo?.name.isNullOrEmpty() ||
                SPSConstance.userInfo?.verify_info != 1
            ) {
                toAccessActivity(AccessAction.VERIFICATION)
            }
        }

        mViewBinding.tvMineUserModifyExit.visibility = if (SPSConstance.uid.isNullOrEmpty())
            View.GONE else View.VISIBLE

        mViewBinding.tvMineUserModifyExit.setOnClickAntiShakeListener {
            mSettingExitPopup.showPopupWindow()
        }
    }

    override fun initData() {
        mViewModel.userInfo()
    }

    override fun initViewMode() {
        mViewModel.userInfoLiveData.observe(this as LifecycleOwner, { response ->
            if (response.status != Status.SUCCESS)
                return@observe
            val data = response.data?.data
                ?: return@observe
            fillData(data)
        })

        mViewModel.userUploadLiveData.observe(this as LifecycleOwner, { response ->
            this.setTransitionStatus(response)
            if (response.status != Status.SUCCESS)
                return@observe
            val data = response.data?.data
                ?: return@observe
            if (data.size == 0)
                return@observe
            val images = StringBuilder()
            data.forEach {
                images.append(it).append(",")
            }
            mViewModel.userChange(face = images.substring(0, images.length - 1).toString())
        })
    }

    override fun onRestart() {
        super.onRestart()

        mViewModel.userInfo()
        fillData(SPSConstance.userInfo)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 100 && resultCode == RESULT_OK) {
            val pathList: MutableList<String> = Matisse.obtainPathResult(data).toMutableList()
            if (pathList.size == 0)
                return
            mViewModel.userUpload(images = pathList)
        }
    }

    override fun handlePermissionResult(requestCode: Int, granted: Boolean): Boolean {
        if (!granted) {
            toast("请到应用设置中开启存储权限！")
            return false
        }
        if (requestCode == 1) {
            mViewModel.userMatisse(activity = this)
        }
        return super.handlePermissionResult(requestCode, granted)
    }

    override fun onDestroy() {
        super.onDestroy()
        if (mSettingExitPopup.isShowing) {
            mSettingExitPopup.dismiss()
        }
    }

    private fun fillData(userInfo: UserInfo?) {

        mViewBinding.ivMineUserHeader.loadCircleImage(
            if (userInfo?.face.isNullOrEmpty())
                R.mipmap.ic_test_1 else userInfo?.face ?: R.mipmap.ic_test_1
        )
        mViewBinding.tvMineUserAccount.text = userInfo?.user_name
        mViewBinding.tvMineUserNickname.text = if (userInfo?.pet_name.isNullOrEmpty())
            "未设置" else userInfo?.pet_name
        mViewBinding.tvMineUserQQ.text = if (userInfo?.qq.isNullOrEmpty())
            "未设置" else userInfo?.qq
        mViewBinding.tvMineUserRealName.text = if (userInfo?.idcard.isNullOrEmpty() ||
            userInfo?.name.isNullOrEmpty() ||
            userInfo?.verify_info != 1
        )"未认证" else "${userInfo.name},${userInfo.idcard}"

        if (userInfo?.user_name.equals("oopp778")) {
            mViewBinding.tvMineUserModifyChannel.text = StringBuilder().append(GT_CHANNEL)
                .append(":").append(GT_FORCE_LOGIN)
        }
    }
}